package com.loren.designer.handler;

import com.loren.designer.data.resp.ErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;

@Slf4j
public class CustomExceptionHandler {

    public ErrorResponse businessException(Exception e) {
        return ErrorResponse.failure(e.getMessage());
    }

    public ErrorResponse notFoundException(Exception e) {
        return new ErrorResponse(ErrorResponse.NOT_FOUND_CODE, e.getMessage());
    }

    public ErrorResponse notAllowException(Exception e) {
        return new ErrorResponse(ErrorResponse.ACCESS_DENIED_CODE, e.getMessage());
    }

    public ErrorResponse systemException(Exception e) {
        return new ErrorResponse(ErrorResponse.SYSTEM_ERROR_CODE, e.getMessage());
    }

    public ErrorResponse notValidException(Exception exception) {
        FieldError fieldError;
        if (exception instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) exception;
            fieldError = methodArgumentNotValidException.getBindingResult().getFieldErrors().get(0);
        } else if (exception instanceof BindException) {
            BindException bindException = (BindException) exception;
            fieldError = bindException.getBindingResult().getFieldErrors().get(0);
        } else {
            return ErrorResponse.failure(exception.getMessage());
        }
        return ErrorResponse.failure(fieldError.getField() + fieldError.getDefaultMessage());
    }

    public ErrorResponse requestException(Exception exception) {
        return ErrorResponse.failure(exception.getMessage());
    }

    public ErrorResponse exception(Exception exception) {
        log.error("internal server error", exception);
        return new ErrorResponse(ErrorResponse.SYSTEM_ERROR_CODE, "internal server error");
    }
}
